package socket;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client1 {
    private Socket socket;
    private PrintWriter out;
    private BufferedReader in;
    private ClientGUI gui;
    private String username;

    public Client1() {
        try {
            System.out.println("正在连接服务端...");
            socket = new Socket("127.0.0.1", 8088);
            System.out.println("连接成功");

            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8)), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));

            gui = new ClientGUI(this);
            gui.setVisible(true);

            // 获取用户名
            username = JOptionPane.showInputDialog(gui, "请输入用户名：");
            while (username == null || username.trim().isEmpty()) {
                username = JOptionPane.showInputDialog(gui, "昵称不能为空，请重新输入：");
            }
            out.println(username);

            // 启动接收消息的线程
            new Thread(this::receiveMessages).start();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void receiveMessages() {
        try {
            String message;
            while ((message = in.readLine()) != null) {
                final String finalMessage = message;
                SwingUtilities.invokeLater(() -> gui.displayMessage(finalMessage));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void sendMessage(String message) {
        out.println(message);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new Client1());
    }

    private class ClientGUI extends JFrame {
        private JTextArea chatArea;
        private JTextField messageField;
        private JButton sendButton;
        private Client1 client;

        public ClientGUI(Client1 client) {
            this.client = client;
            setTitle("Chat Room");
            setSize(600, 400);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            // 创建聊天区域
            chatArea = new JTextArea();
            chatArea.setEditable(false);
            JScrollPane chatScrollPane = new JScrollPane(chatArea);

            // 创建消息输入区域
            messageField = new JTextField();
            sendButton = new JButton("发送");

            // 设置布局
            setLayout(new BorderLayout());
            add(chatScrollPane, BorderLayout.CENTER);

            JPanel bottomPanel = new JPanel(new BorderLayout());
            bottomPanel.add(messageField, BorderLayout.CENTER);
            bottomPanel.add(sendButton, BorderLayout.EAST);
            add(bottomPanel, BorderLayout.SOUTH);

            // 添加发送按钮事件监听器
            sendButton.addActionListener(e -> sendMessage());

            // 添加回车键发送消息
            messageField.addKeyListener(new KeyAdapter() {
                @Override
                public void keyPressed(KeyEvent e) {
                    if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                        sendMessage();
                    }
                }
            });
        }

        private void sendMessage() {
            String message = messageField.getText();
            if (!message.isEmpty()) {
                client.sendMessage(message);
                messageField.setText("");
            }
        }

        public void displayMessage(String message) {
            chatArea.append(message + "\n");
            chatArea.setCaretPosition(chatArea.getDocument().getLength());
        }
    }
}